<?php

namespace app\store\service;

use app\store\model\Goods;
use think\facade\Db;

class GoodsService
{
    /**
     * 获取商品列表
     * */
    public function getGoodsList($param)
    {
        $store_id = session('store_id');

        $model = new Goods();

        $query = $model->field('id,sort,category_id,goods_name,main_image,market_price,sell_price,stock,total_sale,status,create_time,update_time')->with(['category' => function ($query) {
            $query->field('id,name');
        }])->where('store_id', $store_id)->with('category');

        if (isset($param['status']) && $param['status'] != '') {
            $query->where('status', $param['status']);
        }

        if (!empty($param['cid'])) {
            $query->where('category_id', $param['cid']);
        }

        if (!empty($param['keyword'])) {
            $query->whereLike('goods_name', "%{$param['keyword']}%");
        }

        $goods = $query->order('id','desc')->paginate(10);


        return $goods;
    }


    public function getGoodsRecycleList($param)
    {
        $store_id = session('store_id');


        $query = Goods::onlyTrashed()->field('id,sort,category_id,goods_name,main_image,market_price,sell_price,stock,total_sale,status,create_time,update_time')->with(['category' => function ($query) {
            $query->field('id,name');
        }])->where('store_id', $store_id);

        if (isset($param['status']) && $param['status'] != '') {
            $query->where('status', $param['status']);
        }


        if (!empty($param['keyword'])) {
            $query->whereLike('goods_name', "%{$param['keyword']}%");
        }

        $goods = $query->paginate(10);

        return $goods;
    }

    public function goodsRestore($id)
    {
        $goods = Goods::onlyTrashed()->find($id);
        $result = $goods->restore();

        return $result;
    }

    public function getGoodsOptions($param)
    {
        $store_id = session('store_id');

        $query = Goods::field('id,sort,spec_type,goods_name,goods_attr,main_image,market_price,sell_price,stock,total_sale,create_time')
                      ->where(['store_id' => $store_id, 'status' => 1])
                      ->with('items');

        if (!empty($param['cid'])) {
            $query->where('category_id', $param['cid']);
        }

        if (!empty($param['keyword'])) {
            $query->whereLike('goods_name', "%{$param['keyword']}%");
        }

        $goodsOptions = $query->order('id','desc')->paginate(['list_rows' => 10, 'query' => ['type' => $param['type']]]);
        return $goodsOptions;
    }

    /**
     *
     * 获取商品详情
     * */
    public function findGoods($id)
    {
        $model = new Goods();
        $goods = $model->withOutField('create_time,update_time,delete_time')
            ->with(['goodsContent','category','items', 'tags'])->find($id);

        return $goods;
    }


    /**
     *
     * 获取商品选项
     * */
    public function findOptionGoods($id)
    {
        $model = new Goods();
        $goods = $model->withOutField('create_time,update_time,delete_time')
            ->with('items')->find($id);

        return $goods;
    }


    /**
     * 保存商品
     * */
    public function saveGoods($data)
    {
        $skus = [];
        $categoryData = $this->formatGoodsInfo($data,$skus);
        $data['store_id'] = session('store_id');
        $goods = Goods::create($data);

        if ($data['spec_type'] == 2){
            $goods->items()->saveAll($skus);
        }

        $goods->goodsContent()->save($data);

        $goods_id = $goods['id'];

        if (!empty($data['tag_id'])) {
            $this->insertGoodsTag($goods_id,$data['tag_id']);
        }

        $this->saveCategory($categoryData,$goods_id);


        return $goods_id;
    }

    /**
     * 更新商品
     * */
    public function updateGoods($data)
    {   
        $skus = [];

        $categoryData = $this->formatGoodsInfo($data,$skus);

        $goods = Goods::update($data);


        if ($data['spec_type'] == 2){
            $goods->items()->saveAll($skus);
        }

        $goods->goodsContent->where('goods_id',$data['id'])->update(['content' => $data['content']]);



        $goods_id = $goods['id'];

        $this->saveCategory($categoryData,$goods_id,true);

        if(!empty($data['tag_id'])){
            $this->insertGoodsTag($goods_id,$data['tag_id'],true);
        }
        return $goods_id;
    }

    /**
     * 格式化商品信息
     * */
    protected function formatGoodsInfo(&$data,&$skus)
    {
        if ($data['spec_type'] == 2) {
            $skus = json_decode($data['skus'], true);
            $data['market_price'] = min(array_column($skus,'market_price'));
            $data['sell_price'] = min(array_column($skus,'sell_price'));
            $data['subsidy_price'] = min(array_column($skus,'subsidy_price'));
            $data['stock'] =  array_sum(array_column($skus,'stock'));
        }

        $category = explode('-', $data['category_id']);
        array_shift($category);
        $data['category_id'] = end($category);

        if(isset($data['restricted_members']) && !empty($data['restricted_members'])){
            $data['is_limit_member'] = 1;
        } else {
            $data['restricted_members'] = '';
            $data['is_limit_member'] = 0;
        }


        return $category;
    }



    /**
     * 添加商品分类
     * */

    public function saveCategory($arr,$goods_id,$isUpdate = false)
    {

        $cidArr =[];
        foreach ($arr as $k => $v){
            $cidArr[$k]['goods_category_id'] = $v;
            $cidArr[$k]['goods_id'] = $goods_id;
        }

        if ($isUpdate){
            Db::name("goods_mid_category")->where('goods_id',$goods_id)->delete();
        }

        $rows =  Db::name('goods_mid_category')->insertAll($cidArr);

        return $rows;
    }

    /**
     * 添加或更新商品标签
     * */
    protected function insertGoodsTag($goods_id,$tags,$is_update = false)
    {

        if ($is_update) {
            Db::name('goods_mid_tag')->where('goods_id',$goods_id)->delete();
        }

        $data = [];
        foreach($tags as $k => $v){
            $data[$k]['goods_tag_id'] = $v;
            $data[$k]['goods_id'] = $goods_id;
        }

        $rows = Db::name('goods_mid_tag')->insertAll($data);

        return  $rows;
    }


}